'''
Created on 3. 2. 2014

@author: pb
'''
import os
import logging

log = logging.getLogger(__name__)


DBFILE = '/tmp/pokus.db'
ENV_DBFILE = 'LIVENV'
def _get_db_file():
    if os.environ.has_key(ENV_DBFILE):
        return os.environ[ENV_DBFILE]
        return DBFILE;

class Environment:
    
    def __init__(self):
        pass
    
    
    
    def create_db(self):
        db_file = _get_db_file()
        log.debug("creating database: %s" % db_file)
        try :
            conn = Db().get_connection()
            c = conn.cursor();
            c.executescript(open('schema.sql', 'r').read())
            c.close()
        finally:
            conn.close()

import sqlite3 as db

class QueryBuilder:
    
    def __init__(self, query):
        self.query = query
        
    def query(self, params={}):
        s = self.query
        w = " where "  
        for k in params.keys():
            s += ("%s %s=:%s" % (w,k,k))
            w = " and "
        return s
        
class Db:
    
    conn = None
    
    def __init__(self):
        log.debug("Db.__init__")
        self.conn = None

    def __enter__(self):
        log.debug("Db.__enter__")
        return self
    
    def __exit__(self, typ, value, traceback):
        log.debug("Db.__exit__, type=%s, value=%s, traceback=%s" % (typ, value, traceback))
        self.close();
    
    def get_connection(self):
        if (self.conn):
            return self.conn
        conn = db.connect(_get_db_file())
        conn.row_factory = db.Row
        self.conn = conn
        return conn
     
    def close(self):
        if (self.conn):
            self.conn.close()
            self.conn = None




class Query(Db):   
    
    def __init__(self, q, params={}):
        self.query = q
        self.params = params
    
    def __enter__(self):
        log.debug("Query.__enter__: opening query '%s', params: %s" % (self.query, self.params))
        return self.execute(self.get_connection())
    
    def __exit__(self, typ, value, traceback):
        log.debug("Query.__exit__, type=%s, value=%s, traceback=%s" % (typ, value, traceback))
        self.close()
        pass

    def execute(self, conn):
        log.debug("Query.execute")
        return conn.cursor().execute(self.query, self.params)


class RestQuery(Query):
    
    def restrict(self, params={}):
        s = self.query
        w = " where "  
        for k in params.keys():
            s += ("%s %s=:%s" % (w,k,k))
            w = " and "
        return s
        
    def execute(self, conn):
        log.debug("RestQuery.execute: %s, %s" % (self.restrict(self.params), self.params))
        return conn.cursor().execute(self.restrict(self.params), self.params)
    
    
    
class CommitQueries(Db):    
    
    def __init__(self, queries):
        self.queries = queries
        
    def __enter__(self):
        log.debug("CommitQueries.__enter__: executing queries: %s" % self.queries)
        for i in self.queries:
            i.execute(self.get_connection())
           
    def __exit__(self, typ, value, traceback):
        log.debug("CommitQueries.__exit__: exiting transaction query, type=%s, value=%s, traceback=%s" % (typ, value, traceback))
        if (typ):
            log.error("Not commiting: type=%s, value=%s, traceback=%s" % (typ, value, traceback))
        else:
            self.conn.commit()
        self.conn.close();
        